<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

use Doctrine\Common\Util\Debug;

class Customer extends Controller{

	private $sidebar_menu_links = array(
		'detail' => 'Detail',
		'jadwal' => 'Jadwal Kunjungan',
		'checklist' => 'Detail Kunjungan',
	);

    function __construct(){
        parent::Controller();
		$this->current_user = models\Current_user::get_user();
		if(!models\Current_user::get_user()) 
			show_error(array('Halaman ini tidak bisa diakses oleh anda!',anchor('','Kembali ke halaman utama')),403);
    }

    function index(){

        $this->load->library('pagination');

		$total_rows = $this->doctrine->em
			->createQuery('SELECT COUNT(c.id) FROM models\Customer c')
			->getSingleScalarResult();

		$config = array(
			'base_url' =>  base_url().'/'.$this->uri->segment(1).'/index',
			'total_rows' => $total_rows,
			'per_page' => 10,
			'num_links' => 10,
			'full_tag_open' => "<div id='pagination'>",
			'full_tag_close' => "</div>",
		);
		
        $this->pagination->initialize($config);
        
		if(!$this->uri->segment(3)) $offset = 0;
		else $offset = $this->uri->segment(3);

		$customer = $this->doctrine->em
			->createQuery('SELECT c FROM models\Customer c ORDER BY c.username ASC')
			->setMaxResults($config['per_page'])
			->setFirstResult($offset)
			->getResult();

		$this->main_content->add_custom('p','Terdapat '.$total_rows.' customer yang terdaftar ');

		foreach($customer as $c){

			// avatar perusahaan dengan pribadi berbeda
			if(get_class($c) == "models\Perusahaan") 
				$avatar = 'images/pabrik.png';
			else $avatar = 'images/orang.png';

			$block = new Block();

			$grid = $block->add_grid();
			$grid->add_info($c->get_username())
				->add_nama_info($c,$avatar);

			if(models\Current_user::previlege('Administrator')){
				$grid->add_info('Agen: '.anchor('agen/detail/'.$c->get_agen()->get_username(),$c->get_agen()->get_nama()));
			}

			$grid->add_info('Paket: '.$c->get_paket_langganan()->get_nama());

			$block->add_grid()
				->add_info(
					$c->get_alamat().br().
					$c->get_kota().' '.
					$c->get_kodepos().br().
					$c->get_propinsi(),
					'images/rumah.png'
				);

			$block->add_grid()
				->add_info($c->get_telepon(),'images/telepon.png')
				->add_info($c->get_telepon_seluler(),'images/hape.png')
				->add_info($c->get_fax(),'images/fax.png')
				->add_info(mailto($c->get_email()),'images/edit.png');

			$block->set_class('daftar_akun');

			$this->main_content->add_block($block);
		}

		$this->main_content->add_pagination();

		$this->headbar->add_header();

		if(models\Current_user::previlege('Administrator|Agen')){
			$this->headbar->add_menu('register','Pendaftaran Customer Baru',$this->uri->segment(1).'/register');
		}

		$this->sidebar->create_custom('p','Daftar seluruh customer Smart Connect Internet Home Services');
        $this->load->view('template', array('title' => 'Customer'));

    }

    function register(){

		if(models\Current_user::previlege('Administrator|Agen')){

			// mendapatkan data untuk option dropdown
			$this->config->load('dropdown_options');
			$option_jenis_pelanggan = $this->config->item('jenis_pelanggan');
			$option_propinsi = $this->config->item('propinsi');
			$option_paket_langganan = models\Paket_langganan::get_dropdown_options();

			if(models\Current_user::previlege('Administrator')){
				$option_agen = models\Agen::get_dropdown_options();

				$this->main_content->add_block('Agen')
					->add_dropdown_field('agen','Agen',$option_agen);
			}

			$this->main_content->add_block('Akun')
				->add_username_field('models\Customer')
				->add_text_field('nama','Nama')
				->add_dropdown_field('jenis_customer','Jenis Customer',$option_jenis_pelanggan)
				->add_dropdown_field('paket_langganan','Paket Langganan',$option_paket_langganan);

			$this->main_content->add_block('Info Perusahaan/Customer')
				->add_text_field('jenis_usaha','Jenis Usaha','','perusahaan_only')
				->add_text_field('penanggung_jawab','Penanggung Jawab','','perusahaan_only')
				->add_identitas_field()
				->add_text_field('jabatan','Jabatan','','perusahaan_only')
				->add_text_field('npwp','NPWP','','perusahaan_only')
				->add_custom_field('Website','<span>http://</span>'.form_input('website'),'perusahaan_only');

			$this->main_content->add_block('Alamat')
				->add_text_field('alamat','Alamat')
				->add_text_field('kota','Kota')
				->add_text_field('kodepos','Kode Pos')
				->add_dropdown_field('propinsi','Propinsi',$option_propinsi); 

			$this->main_content->add_block('Kontak')
				->add_text_field('telepon','Telepon')
				->add_text_field('email','Email');

			$this->main_content->add_block('Kontak')
				->add_textarea_field('keterangan','Keterangan');

			$this->main_content->set_form_register();

			$this->headbar->add_header();
			$this->sidebar->create_custom('p','Username dan password akan otomatis dikirim ke alamat email yang diinputkan');

			$this->load->view('template',array('title' => 'Register Customer'));

		} else 
			show_error(array('Halaman ini tidak bisa diakses oleh anda!',anchor('','Kembali ke halaman utama')),403);
    }

	function ajax_register(){
		if(IS_AJAX){

			$this->load->library('form_validation');

			if($this->form_validation->run('pelanggan') == TRUE){

				if($this->input->post('jenis_customer') == 'perusahaan'){
					$customer = new models\Perusahaan();
					$customer->set_penanggung_jawab($this->input->post('penanggung_jawab'));
					$customer->set_jabatan($this->input->post('jabatan'));
					$customer->set_jenis_usaha($this->input->post('jenis_usaha'));
					$customer->set_npwp($this->input->post('npwp'));
					$customer->set_website($this->input->post('website'));
				} else {
					$customer = new models\Customer();
				}

				//generate username & password
				$this->load->library('generator');
				if($this->input->post('tipe_username') == 'manual')
					$username = $this->generator->generate_username('models\Customer',$this->input->post('username'));
				else $username = $this->generator->generate_username('models\Customer');
				$password = $this->generator->generate_password();
				$customer->set_username($username);
				$customer->set_password($password);

				//detail_langganan
				$paket_langganan = $this->doctrine->em->find('models\Paket_langganan',$this->input->post('paket_langganan'));
				$customer->set_paket_langganan($paket_langganan);

				if(models\Current_user::previlege('Agen'))
					$agen = $this->current_user;
				else $agen = $this->doctrine->em->find('models\Agen',$this->input->post('agen'));

				$customer->set_agen($agen);

				//akun
				$customer->set_nama($this->input->post('nama'));

				//identitas
				$customer->set_jenis_identitas($this->input->post('jenis_identitas'));
				$customer->set_no_identitas($this->input->post('no_identitas'));

				//alamat
				$customer->set_alamat($this->input->post('alamat'));
				$customer->set_kodepos($this->input->post('kodepos'));
				$customer->set_kota($this->input->post('kota'));
				$customer->set_propinsi($this->input->post('propinsi'));

				//kontak
				$customer->set_telepon($this->input->post('telepon'));
				$customer->set_telepon_seluler($this->input->post('telepon_seluler'));
				$customer->set_fax($this->input->post('fax'));
				$customer->set_email($this->input->post('email'));

				//lain-lain
				$customer->set_keterangan($this->input->post('keterangan'));

				//insert ke database
				$this->doctrine->em->persist($customer);
				$this->doctrine->em->flush();

				$this->load->library('email_gateway');
				$email = $this->input->post('email');
				$log_email = $this->email_gateway->send_new_akun_email($email, $username, $password);

				$returned_data = array(
					'status' => 'sukses',
					//'log_email' => $log_email,
				);

				$this->session->set_flashdata('status', 'Berhasil manambah customer '.$this->input->post('nama')."! <br /> Username dan password telah terkirim ke email customer");
			} else {

				$returned_data = array(
					'status' => 'gagal',
					'error' => validation_errors(),
				);
			}

			echo json_encode($returned_data);

		} else show_404(); 
	}
	
    function detail($username = null){
		if(!$username) show_404();
		
		// melakukan DQL untuk mengambil Customer berdasarkan input username
		$customer = $this->doctrine->em->getRepository('models\Customer')->findOneBy(array('username' => $username));
		if(!$customer) show_404();

		//mendapatkan jenis customer
		$jenis_customer = substr(get_class($customer),7);

		$block = $this->main_content->add_block('Akun');
		$block->add_hidden_field('id',$customer->get_id())
			->add_editable_username($customer)
			->add_editable_data('nama','Nama',$customer->get_nama());

		if(models\Current_user::previlege('Administrator'))
			$block->add_editable_agen($customer->get_agen());
		else $block->add_data('Agen',$customer->get_agen()->get_nama());

		// membedakan antara customer pribadi dan perusahaan
		if($jenis_customer == "Perusahaan"){ 

			$img = 'images/pabrik.png';
			$website = anchor('http://'.$customer->get_website(),$customer->get_website());

			$this->main_content->add_block('Info Perusahaan')
				->add_editable_data('jenis_usaha','Jenis Usaha',$customer->get_jenis_usaha())
				->add_editable_data('penanggung_jawab','Penanggung Jawab',$customer->get_penanggung_jawab())
				->add_editable_identitas($customer)
				->add_editable_data('jabatan','Jabatan',$customer->get_jabatan())
				->add_editable_data('npwp','NPWP',$customer->get_npwp())
				->add_editable_website($customer->get_website());

		} else {
			$img = 'images/orang.png';
			$this->main_content->add_block('Info Customer')
				->add_editable_identitas($customer);
		}

		$this->main_content->add_block('Alamat')
			->add_editable_data('alamat','Alamat',$customer->get_alamat())
			->add_editable_data('kota','Kota',$customer->get_kota())
			->add_editable_data('kodepos','Kode Pos',$customer->get_kodepos())
			->add_editable_propinsi($customer->get_propinsi());

		$this->main_content->add_block('Kontak')
			->add_editable_data('telepon','No Telepon',$customer->get_telepon())
			->add_editable_data('telepon_seluler','No HP',$customer->get_telepon_seluler())
			->add_editable_data('fax','No Fax',$customer->get_fax())
			->add_editable_email($customer->get_email());

		$this->main_content->add_block('Keterangan')
			->add_editable_textarea_data('keterangan','Keterangan',$customer->get_keterangan());

		if(models\Current_user::previlege('Administrator|Agen')){
			$this->main_content->set_editable();
			$this->main_content->set_deletable();
		}

		$this->headbar->add_header();

		$this->sidebar
			->create_identitas($customer)
			->create_menu($this->sidebar_menu_links);

        $this->load->view('template',array('title' => 'Info customer'));
    }

	function ajax_edit($username = null){
		if(IS_AJAX){

			$this->load->library('form_validation');

			if($this->form_validation->run('pelanggan_update') == TRUE){

				$customer = $this->doctrine->em
					->getRepository('models\Customer')
					->findOneBy(array('username' => $username));

				if(!$customer) {
					$returned_data = array('status' => 'gagal');
					echo json_encode($returned_data);
					return false;
				}

				$agen = $this->doctrine->em
					->getRepository('models\Agen')
					->findOneBy(array('id' => $this->input->post('agen')));

				$this->load->library('generator');
				$username = $this->generator->generate_username('models\Customer',$this->input->post('username'));

				$customer->set_username($username);
				$customer->set_nama($this->input->post('nama'));
				$customer->set_agen($agen);
				$customer->set_jenis_identitas($this->input->post('jenis_identitas'));
				$customer->set_no_identitas($this->input->post('nomor_identitas'));
				$customer->set_alamat($this->input->post('alamat'));
				$customer->set_kota($this->input->post('kota'));
				$customer->set_kodepos($this->input->post('kodepos'));
				$customer->set_propinsi($this->input->post('propinsi'));
				$customer->set_telepon($this->input->post('telepon'));
				$customer->set_telepon_seluler($this->input->post('telepon_seluler'));
				$customer->set_fax($this->input->post('fax'));
				$customer->set_email($this->input->post('email'));
				$customer->set_keterangan($this->input->post('keterangan'));

				//field khusus perusahaan, harus dicek ada tidaknya
				if($this->input->post('jenis_usaha')) $customer->set_jenis_usaha($this->input->post('jenis_usaha'));
				if($this->input->post('penanggung_jawab')) $customer->set_penanggung_jawab($this->input->post('penanggung_jawab'));
				if($this->input->post('jabatan')) $customer->set_jabatan($this->input->post('jabatan'));
				if($this->input->post('npwp')) $customer->set_npwp($this->input->post('npwp'));
				if($this->input->post('website')) $customer->set_website($this->input->post('website'));

				$this->doctrine->em->flush();

				$returned_data = array(
					'status' => 'sukses',
					'username' => $username,
				);

			} else {
				$returned_data = array(
					'status' => 'gagal',
					'error' => validation_errors(),
				);
			}

			echo json_encode($returned_data);

		} else show_404();
	}
	
	function ajax_hapus(){
		
		if(IS_AJAX){
		
			$username = $this->input->post('username');

			$customer = $this->doctrine->em->getRepository('models\Customer')->findOneBy(array('username' => $username));
			$this->doctrine->em->remove($customer);
			$this->doctrine->em->flush();

			$this->session->set_flashdata('status', 'Berhasil menghapus customer '.$username);

		} else show_404();
    }
	
	function jadwal($username = null, $tahun = null, $bulan = null){
		if(!$username) show_404();
		
		// melakukan DQL untuk mengambil Customer berdasarkan input username
		$customer = $this->doctrine->em->getRepository('models\Customer')->findOneBy(array('username' => $username));
		if(!$customer) show_404();

		if(!$tahun) $tahun = date('Y');
		if(!$bulan) $bulan = date('m');
		
		$this->config->load('calendar');

		$kunjungan= $this->doctrine->em->createQuery("
			SELECT k 
			FROM models\Kunjungan k 
			JOIN k.customer c 
			WHERE c.username = '$username' 
			AND k.tanggal LIKE '$tahun-$bulan%' 
			")->getResult();

		$cal_data = array();
		if(count($kunjungan) > 0){
			foreach($kunjungan as $k){
				$tanggal = $k->get_tanggal()->format('d');
				settype($tanggal,'integer');
				$cal_data[$tanggal] = 
					$k->get_teknisi()->get_username().'<br />'.
					$k->get_teknisi()->get_nama();
			}
		}

		$this->load->library('calendar',array(
			'start_day' => 'monday',
			'show_next_prev' => true,
			'next_prev_url' => base_url().$this->uri->segment(1).'/'.$this->uri->segment(2).'/'.$username,
			'template' => $this->config->item('calendar_template'),
		));
		
		$calendar = $this->calendar->generate($tahun, $bulan, $cal_data);
		
		$this->main_content->add_calendar($calendar);

		$this->headbar->add_header();
		$this->sidebar
			->create_identitas($customer)
			->create_menu($this->sidebar_menu_links);
		
        $this->load->view('template', array('title' => 'Jadwal Kunjungan customer'));
	}
	
	function checklist($username = null, $tahun = null, $bulan = null, $hari = null){
		if(!$username) show_404();
		
		// melakukan DQL untuk mengambil Customer berdasarkan input username
		$customer = $this->doctrine->em->getRepository('models\Customer')->findOneBy(array('username' => $username));
		if(!$customer) show_404();

		if(!$tahun) $tahun = date('Y');
		if(!$bulan) $bulan = date('m');
		if(!$hari) $hari = date('d');
		
		$tanggal = "$tahun-$bulan-$hari";
		$tanggal_obj = new Datetime("$tahun-$bulan-$hari");
		$title = 'Detail Kunjungan '.$tanggal_obj->format('d M Y');

		$array_kunjungan = $this->doctrine->em->createQuery("
			SELECT k 
			FROM models\Kunjungan k 
			JOIN k.customer c 
			WHERE c.username = '$username' 
			AND k.tanggal LIKE '$tanggal%'
			")->getResult();
		$kunjungan_id = '';

		if(count($array_kunjungan) > 0){

			$this->creator->create_detail_kunjungan_page($array_kunjungan[0]);
			$kunjungan = $array_kunjungan[0];
			$kunjungan_id = $kunjungan->get_id();

		} else {

			$this->main_content->add_custom('p','Tidak ada data Kunjungan untuk '.$customer->get_nama().' pada '.$tanggal_obj->format('D, d M Y'));
			$this->headbar->add_menu('tambah_kunjungan','+ kunjungan',"customer/ajax_tambah_kunjungan/$username/$tanggal");

			if(models\Current_user::previlege('Administrator|Agen')){
				$option_teknisi = models\Teknisi::get_dropdown_options();
				$this->main_content->add_block()
					->add_dropdown_field('teknisi','Pasang teknisi di hari ini',$option_teknisi)
					->set_form("customer/ajax_tambah_kunjungan/$username/$tanggal",'add_teknisi')
					->set_id('tambah_kunjungan_block')
					->set_style("display: none");
			}
		}

		$this->main_content->add_script('checklist');

		$this->headbar->add_header(anchor($this->uri->segment(1),'Customer').' > '.$title);
		$this->sidebar
			->create_identitas($customer)
			->create_menu($this->sidebar_menu_links)
			->add_custom('p','Untuk ganti tanggal, klik tanggal dibawah ini');

		$cal_data = models\Kunjungan::get_calendar_data($tahun,$bulan,$username);
		$calendar_url = base_url().$this->uri->segment(1)."/ajax_checklist_calendar/$username";
		$calendar = $this->creator->create_calendar($tahun,$bulan,$calendar_url,$cal_data);
		$this->sidebar->add_calendar($calendar);
		$this->main_content->add_script('checklist_calendar');

		$day_link = base_url()."customer/checklist/$username";
		
		$this->load->view('template', array(
			'title' => $title,
			'kunjungan_id' => $kunjungan_id,
			'day_link' => $day_link,
			'hari' => $hari,
			'bulan' => $bulan,
			'tahun' => $tahun,
		));
	}

	function ajax_get_default_objek($id_jenis_device){
		if(IS_AJAX){

			$jenis_device = $this->doctrine->em
				->getRepository('models\Jenis_device')
				->findOneBy(array('id' => $id_jenis_device));

			$objek = $jenis_device->get_objek_pengecekan();

			foreach ($objek as $row) {
				$returned_data[] = $row->get_nama();
			}

			echo json_encode($returned_data);

		} else show_404();
	}

	function ajax_checklist_calendar($username,$tahun,$bulan){
		if(IS_AJAX){

			$cal_data = models\Kunjungan::get_calendar_data($tahun,$bulan,$username);
			$calendar_url = base_url().$this->uri->segment(1)."/ajax_checklist_calendar/$username";
			$calendar = $this->creator->create_calendar($tahun,$bulan,$calendar_url,$cal_data);
			echo $calendar;

		} else show_404();
	}

	function ajax_tambah_kunjungan($username,$tanggal){
		if(IS_AJAX){

			$customer = $this->doctrine->em
				->getRepository('models\Customer')
				->findOneBy(array('username' => $username));
			$tanggal = new Datetime($tanggal);

			if(models\Current_user::previlege('Teknisi')){
				$teknisi = $this->current_user;
			} else {
				$teknisi = $this->doctrine->em
					->getRepository('models\Teknisi')
					->findOneBy(array('id' => $this->input->post('teknisi')));
			}

			$array_kunjungan = $this->doctrine->em
				->createQuery('SELECT k FROM models\Kunjungan k ORDER BY k.flex_id')
				->getResult();

			$last_flex_id = $array_kunjungan[count($array_kunjungan)-1]->get_flex_id();
			$new_id = $last_flex_id + 1;

			$kunjungan = new models\Kunjungan();
			$kunjungan->set_flex_id($new_id);
			$kunjungan->set_customer($customer);
			$kunjungan->set_tanggal($tanggal);
			$kunjungan->set_teknisi($teknisi);

			$this->doctrine->em->persist($kunjungan);
			$this->doctrine->em->flush();

			$returned_data = array('status' => 'sukses');
			echo json_encode($returned_data);

		} else show_404();
	}

	function ajax_hapus_kunjungan($id_kunjungan){
		if(IS_AJAX){
			$kunjungan = $this->doctrine->em
				->getRepository('models\Kunjungan')
				->findOneBy(array('id' => $id_kunjungan));
			$this->doctrine->em->remove($kunjungan);
			$this->doctrine->em->flush();
		} else show_404(); 
	}

	function ajax_tambah_checklist($id_kunjungan = ''){
		if(IS_AJAX){

			$kunjungan = $this->doctrine->em
				->getRepository('models\Kunjungan')
				->findOneBy(array('id' => $id_kunjungan));

			$checklist = new models\Checklist();
			$checklist->set_kunjungan($kunjungan);
			$new_dl = array();

			foreach ( $_POST as $key => $value ){
				if($key == 'jenis_device'){
					$jenis_device = $this->doctrine->em
						->getRepository('models\Jenis_device')
						->findOneBy(array('id' => $this->input->post('jenis_device')));
					$checklist->set_jenis_device($jenis_device);
					continue;
				} else if($key == 'nama_device'){
					$checklist->set_nama_device($this->input->post('nama_device'));
					continue;
				} 

				$nomer = substr($key,8);
				$tipe = substr($key,0,7);

				if($tipe == 'newnama') $new_dl[$nomer]['nama'] = $this->input->post($key);
				else if($tipe == 'newkond') $new_dl[$nomer]['kondisi'] = $this->input->post($key);
				else if($tipe == 'newrema') $new_dl[$nomer]['remarks'] = $this->input->post($key);
			}

			if(count($new_dl) > 0){
				foreach($new_dl as $row){
					$dl = new models\Detail_checklist(); 
					$dl->set_nama_objek($row['nama']);
					$dl->set_kondisi($row['kondisi']);
					$dl->set_remarks($row['remarks']);
					$dl->set_checklist($checklist);
					$this->doctrine->em->persist($dl);
				}
			}

			$this->doctrine->em->persist($checklist);
			$this->doctrine->em->flush();

			$block = $this->creator->create_checklist_block($checklist,true);
			echo $block;

		} else show_404(); 
	}

	function ajax_edit_checklist($id_checklist){
		if(IS_AJAX){

			$checklist = $this->doctrine->em
				->getRepository('models\Checklist')
				->findOneBy(array('id' => $id_checklist));

			$new_dl = array();

			foreach ( $_POST as $key => $value ){
				
				if($key == 'jenis_device'){
					$jenis_device = $this->doctrine->em
						->getRepository('models\Jenis_device')
						->findOneBy(array('id' => $this->input->post('jenis_device')));
					$checklist->set_jenis_device($jenis_device);
					continue;
				} else if($key == 'nama_device'){
					$checklist->set_nama_device($this->input->post('nama_device'));
					continue;
				} 

				$nomer = substr($key,8);
				$tipe = substr($key,0,7);

				if( $tipe == 'kondisi' || $tipe == 'remarks' || $tipe == 'deletee'){

					$dl = $this->doctrine->em
						->getRepository('models\Detail_checklist')
						->findOneBy(array('id' => $nomer));

					if(!$dl) continue;

					if($tipe == 'kondisi') $dl->set_kondisi($this->input->post($key));
					else if($tipe == 'remarks') $dl->set_remarks($this->input->post($key));
					else if($tipe == 'deletee') $this->doctrine->em->remove($dl);

				} else if( $tipe == 'newnama' || $tipe == 'newkond' || $tipe == 'newrema'){

					if($tipe == 'newnama') $new_dl[$nomer]['nama'] = $this->input->post($key);
					else if($tipe == 'newkond') $new_dl[$nomer]['kondisi'] = $this->input->post($key);
					else if($tipe == 'newrema') $new_dl[$nomer]['remarks'] = $this->input->post($key);

				}
			} 

			if(count($new_dl) > 0){
				foreach($new_dl as $row){
					$dl = new models\Detail_checklist(); 
					$dl->set_nama_objek($row['nama']);
					$dl->set_kondisi($row['kondisi']);
					$dl->set_remarks($row['remarks']);
					$dl->set_checklist($checklist);
					$this->doctrine->em->persist($dl);
				}
			}

			$this->doctrine->em->flush();

			$block = $this->creator->create_checklist_block($checklist,true);
			echo $block;

		} else show_404(); 
	}

	function ajax_hapus_checklist($id_checklist){
		if(IS_AJAX){
			$checklist = $this->doctrine->em
				->getRepository('models\Checklist')
				->findOneBy(array('id' => $id_checklist));
			$this->doctrine->em->remove($checklist);
			$this->doctrine->em->flush();
		} else show_404(); 
	}

}
